import * as echarts from '../../../../ec-canvas/echarts';

const app = getApp()
const constant = require("../../../../constant.js")
const storage = require("../../../../utils/storage.js")

function setOption(chart, data, datetime, name, subtext, interval) {

  const option = {
    title: {
      text: name,
      subtext: subtext,
      textStyle: {
        color: '#ffffff',
        fontSize: "17",
        fontWeight: 'bold',
        lineHeight: 20,
        verticalAlign: 'top',
      },
      subtextStyle: {
        color: "#ffffff",
        fontSize: "15",
      },
      top: '8%',
      right: '4%',
      backgroundColor: '#333',
      itemGap: 4
    },
    tooltip: {
      trigger: 'none',
      axisPointer: {
        type: 'cross'
      }
    },
    grid: {
      left: '5%',
      top: '20%',
      right: '8%',
      bottom: '10%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: true,
        nameGap: 15,
        axisLine: {
          lineStyle: {
            color: '#ffffff'
          }

        },
        axisTick: {
          show: false,
        },
        axisPointer: {
          label: {
            formatter: function (params) {
              return params.seriesData[0].data;
            },
            margin: -140,
            color: '#000',
            backgroundColor: 'rgba(254, 220, 50, 1)',
            borderColor: 'rgba(254, 220, 50, 1)'
          }
        },
        data: datetime
      }
    ],
    yAxis: [
      {
        type: 'value',
        min: function (value) {
          // return (parseInt(value.min / interval) - 1) * interval;
          return parseInt(value.min - 1);
        },
        max: function (value) {
          // return (parseInt(value.max / interval) + 1) * interval;
          return parseInt(value.min - 1) + interval * 2;
        },
        interval: interval,
        nameGap: 15
      }
    ],
    dataZoom: [
      {
        type: 'inside',
        filterMode: 'empty',
        start: 100 - parseInt(7 * 100 / data.length),
        end: 100
      }
    ],
    series: [
      {
        type: 'line',
        symbol: 'emptyCircle',
        symbolSize: 8,
        itemStyle: {
          borderColor: "#ffde00"
        },
        lineStyle: {
          color: '#ffde00',
        },
        areaStyle: {
          normal: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
              offset: 0,
              color: 'rgba(255,222,0,.3)'
            },
            {
              offset: .5,
              color: 'rgba(255,222,0,.05)'
            },
            {
              offset: 1,
              color: 'rgba(255,222,0,0)'
            }])
          }
        },
        data: data
      }

    ],
    textStyle: {
      color: '#ffffff',
    },
  };
  chart.setOption(option);
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    bmi: {
      lazyLoad: true
    },
    weight: {
      lazyLoad: true
    },
    muscle: {
      lazyLoad: true
    },
    bf: {
      lazyLoad: true
    },
    bfr: {
      lazyLoad: true
    },
    whr: {
      lazyLoad: true
    },
    bm: {
      lazyLoad: true
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      host: constant.api(app.globalData.pord).url,
      mobile: wx.getStorageSync(storage.keys.mobile),
      courseRoundId: options.courseRoundId
    })

    this.bmiComponent = this.selectComponent("#bmi-dom-line")
    this.weightComponent = this.selectComponent("#weight-dom-line")
    this.muscleComponent = this.selectComponent("#muscle-dom-line")
    this.bfComponent = this.selectComponent("#bf-dom-line")
    this.bfrComponent = this.selectComponent("#bfr-dom-line")
    this.whrComponent = this.selectComponent("#whr-dom-line")
    this.bmComponent = this.selectComponent("#bm-dom-line")
  },

  generateData: function (data) {
    let bmiData = [];
    let weightData = [];
    let skeletalMuscleData = [];
    let bfData = [];
    let bfrData = [];
    let whrData = [];
    let bmData = [];

    let inbodyTime = [];

    for (let v of data) {
      bmiData.push(v.bmi.toFixed(2))
      weightData.push(v.weight.toFixed(2))
      skeletalMuscleData.push(v.sm.toFixed(2))
      bfData.push(v.bf.toFixed(2))
      bfrData.push((v.bfr * 100).toFixed(2))
      whrData.push(v.whr.toFixed(2))
      bmData.push(v.bm.toFixed(2))

      inbodyTime.push(v.record_time.substring(5, 7) + "." + v.record_time.substring(8, 10))
    }
    return {
      bmiData: bmiData,
      weightData: weightData,
      skeletalMuscleData: skeletalMuscleData,
      bfData: bfData,
      bfrData: bfrData,
      whrData: whrData,
      bmData: bmData,
      inbodyTime: inbodyTime
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.showLoading({
      title: "正在加载中..."
    })

    var that = this;

    wx.request({
      url: that.data.host + '/coach/course-rounds/' + that.data.courseRoundId + '/inbodys?mobile=' + that.data.mobile,
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: function (res) {
        if (res.data.code == "0") {
          if (res.data.data.inbodys && res.data.data.inbodys.length > 0) {
            that.setData({
              inbodyData: res.data.data.inbodys,
              display: 'block'
            });

            var inbodyData = that.generateData(res.data.data.inbodys);

            that.bmiComponent.init((canvas, width, height) => {

              const chart = echarts.init(canvas, null, {
                width: width,
                height: height
              });

              const arr = inbodyData.bmiData;

              setOption(chart, inbodyData.bmiData, inbodyData.inbodyTime, "BMI", '', Math.ceil((Math.max(...arr) - Math.min(...arr)) / 2 + 1));
              that.chart = chart;
              return chart;
            });

            that.weightComponent.init((canvas, width, height) => {

              const chart = echarts.init(canvas, null, {
                width: width,
                height: height
              });

              const arr = inbodyData.weightData;


              setOption(chart, inbodyData.weightData, inbodyData.inbodyTime, "体重", "kg", Math.ceil((Math.max(...arr) - Math.min(...arr)) / 2 + 1));
              that.chart = chart;
              return chart;
            });

            that.muscleComponent.init((canvas, width, height) => {

              const chart = echarts.init(canvas, null, {
                width: width,
                height: height
              });

              const arr = inbodyData.skeletalMuscleData;


              setOption(chart, inbodyData.skeletalMuscleData, inbodyData.inbodyTime, "骨骼肌", "kg", Math.ceil((Math.max(...arr) - Math.min(...arr)) / 2 + 1));
              that.chart = chart;
              return chart;
            });

            that.bfComponent.init((canvas, width, height) => {

              const chart = echarts.init(canvas, null, {
                width: width,
                height: height
              });

              const arr = inbodyData.bfData;


              setOption(chart, inbodyData.bfData, inbodyData.inbodyTime, "体脂肪", '', Math.ceil((Math.max(...arr) - Math.min(...arr)) / 2 + 1));
              that.chart = chart;
              return chart;
            });

            that.bfrComponent.init((canvas, width, height) => {

              const chart = echarts.init(canvas, null, {
                width: width,
                height: height
              });

              const arr = inbodyData.bfrData;


              setOption(chart, inbodyData.bfrData, inbodyData.inbodyTime, "体脂率", '%', Math.ceil((Math.max(...arr) - Math.min(...arr)) / 2 + 1));
              that.chart = chart;
              return chart;
            });

            that.whrComponent.init((canvas, width, height) => {

              const chart = echarts.init(canvas, null, {
                width: width,
                height: height
              });

              const arr = inbodyData.whrData;


              setOption(chart, inbodyData.whrData, inbodyData.inbodyTime, "腰臀比", '', Math.ceil((Math.max(...arr) - Math.min(...arr)) / 2 + 1));
              that.chart = chart;
              return chart;
            });

            that.bmComponent.init((canvas, width, height) => {

              const chart = echarts.init(canvas, null, {
                width: width,
                height: height
              });

              const arr = inbodyData.bmData;


              setOption(chart, inbodyData.bmData, inbodyData.inbodyTime, "基础代谢", '', Math.ceil((Math.max(...arr) - Math.min(...arr)) / 2 + 1));
              that.chart = chart;
              return chart;
            });
          } else {
            that.setData({
              inbodyData: res.data.data.inbodys,
              display: 'none'
            });
          }

          wx.hideLoading();
        } else {
          wx.hideLoading();

          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 1000
          })
        }
      },
      fail: function (res) {
        wx.hideLoading();

        wx.showToast({
          title: '请求数据失败',
          icon: 'none',
          duration: 1000
        });
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})